//****************************************************************
//* Copyright (c) 2004 Ford Motor Company. All Rights Reserved.
//*
//* $$Workfile:   MixLogDao.java  $$
//* $$Revision:   1.0  $$
//* $$Author:   aponte  $$
//* $$Date:   Dec 10 2008 10:59:58  $$
//*
//*****************************************************************
package ar.com.ford.it.fullEconomics.persistence.dao;

import java.io.FileNotFoundException;
import java.sql.Timestamp;
import java.util.Collection;
import java.util.Iterator;
import oracle.toplink.expressions.Expression;
import oracle.toplink.expressions.ExpressionBuilder;
import oracle.toplink.queryframework.ReadAllQuery;
import oracle.toplink.sessions.Session;
import oracle.toplink.tools.sessionmanagement.SessionManager;
import ar.com.ford.it.fullEconomics.FullEconomicsPrs;
import ar.com.ford.it.fullEconomics.persistence.dto.Ncas012VehicleVw;
import ar.com.ford.it.fullEconomics.persistence.dto.Ncas104SfiVw;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesg01Plant;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp01Part;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp09Mixlog;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp10Mixevent;
import ar.com.ford.it.fullEconomics.wslx.FullEconomicsWslxUser;
import ar.com.ford.it.webengine.persistence.PersistenceUtil;
import com.ford.it.logging.ILogger;
import com.ford.it.logging.Level;
import com.ford.it.logging.LogFactory;
import com.ford.it.persistence.PersistenceException;
import com.ford.it.persistence.Transaction;

public class MixLogDao extends Dao {
	private static final String CLASS_NAME = MixLogDao.class.getName();

	private static final ILogger log = LogFactory.getInstance().getLogger(
			CLASS_NAME);

	/**
	 * Obtiene todos los mix pendientes
	 * 
	 * @param teesg01Plant
	 * @return
	 * @throws PersistenceException
	 */
	@SuppressWarnings("unchecked")
	public Collection<Teesp09Mixlog> findPendientes(Teesg01Plant teesg01Plant)
			throws PersistenceException {

		String METHOD_NAME = "findPendientes";
		log.entering(CLASS_NAME, METHOD_NAME);

		Collection<Teesp09Mixlog> resultCol = null;

		Session session = null;

		try {
			session = SessionManager.getManager().getSession(
					this.getSessionName());
		} catch (FileNotFoundException e) {
			throw new PersistenceException(e);
		}
		ExpressionBuilder builder = new ExpressionBuilder();
		ReadAllQuery query = new ReadAllQuery(Teesp09Mixlog.class);

		Expression exp = null;

		exp = builder.get("eesp09MlogProcStatusCodeC").equal(
				FullEconomicsPrs.CODE.MIX_LOG_STATUS_PENDING);

		exp = exp.and(builder.get("eesp09PlantCodeC").equal(teesg01Plant));

		query.setSelectionCriteria(exp);

		resultCol = (Collection<Teesp09Mixlog>) session.executeQuery(query);

		log.exiting(CLASS_NAME, METHOD_NAME);
		return resultCol;
	}

	/**
	 * Cancela si es que hay un mix pendiente previo.
	 * 
	 * @param teesg01Plant
	 * @return
	 * @throws PersistenceException
	 */
	@SuppressWarnings("unchecked")
	public Collection<Teesp09Mixlog> cancelPendientesByPlantDateVehicle(
			Teesg01Plant teesg01Plant, Timestamp fecha,
			Ncas012VehicleVw vehicleLine, FullEconomicsWslxUser user)
			throws PersistenceException {

		String METHOD_NAME = "cancelPendientesByPlantDateVehicle";
		log.entering(CLASS_NAME, METHOD_NAME);

		Collection<Teesp09Mixlog> resultCol = null;

		Session session = null;

		try {
			session = SessionManager.getManager().getSession(
					this.getSessionName());
		} catch (FileNotFoundException e) {
			throw new PersistenceException(e);
		}
		ExpressionBuilder builder = new ExpressionBuilder();
		ReadAllQuery query = new ReadAllQuery(Teesp09Mixlog.class);

		Expression exp = null;

		exp = builder.get("eesp09MlogProcStatusCodeC").equal(
				FullEconomicsPrs.CODE.MIX_LOG_STATUS_PENDING);

		exp = exp.and(builder.get("eesp09PlantCodeC").equal(teesg01Plant));

		exp = exp.and(builder.get("eesp09VehicleCodeC")
				.equal(vehicleLine));

		exp = exp.and(builder.get("eesp09MlogEffectiveDateY").equal(fecha));

		query.setSelectionCriteria(exp);

		resultCol = (Collection<Teesp09Mixlog>) session.executeQuery(query);

		// Itero y voy cancelando
		for (Iterator iter = resultCol.iterator(); iter.hasNext();) {
			Teesp09Mixlog teesp09Mixlog = (Teesp09Mixlog) iter.next();
			Teesp09Mixlog teesp09Mixlog2 = this.getMixLogForUpdate(
					teesp09Mixlog.getEesp09PlantCodeC(), teesp09Mixlog
							.getEesp09VehicleCodeC(), teesp09Mixlog
							.getEesp09MlogEffectiveDateY(), teesp09Mixlog
							.getEesp09MlogSequenceK());
			teesp09Mixlog2.setEesp09LastUpdtProcessC(new Timestamp(System
					.currentTimeMillis()));
			//teesp09Mixlog2.setEesp09LastUpdtProcessC("MIXPROC");
			teesp09Mixlog2.setEesp09LastUpdtS(new Timestamp(System
					.currentTimeMillis()));
			teesp09Mixlog2.setEesp09LastUpdtUserC(user.getId());
			teesp09Mixlog2.setEesp09MlogEndS(new Timestamp(System
					.currentTimeMillis()));

			teesp09Mixlog2
					.setEesp09MlogProcStatusCodeC(FullEconomicsPrs.CODE.MIX_LOG_STATUS_CANCELLED);
		}

		log.exiting(CLASS_NAME, METHOD_NAME);
		return resultCol;
	}

	/**
	 * Graba un MixLog
	 * 
	 * @param mixr
	 * @throws PersistenceException
	 */
	public void createMixLog(Teesp09Mixlog teesp09Mixlog)
			throws PersistenceException {
		String METHOD_NAME = "createMixLog";
		log.entering(CLASS_NAME, METHOD_NAME);

		Transaction tx = null;

		tx = PersistenceUtil.getTransaction();
		tx.registerInsert(teesp09Mixlog);

		log.exiting(CLASS_NAME, METHOD_NAME);
	}

	/**
	 * Devuelve el mixlog para realizarle las actualizaciones pertinentes
	 * 
	 * @param
	 * @return
	 * @throws PersistenceException
	 */
	public Teesp09Mixlog getMixLogForUpdate(Teesg01Plant plant,
			Ncas012VehicleVw vehiclelin, Timestamp fecha, int seqNumber)
			throws PersistenceException {

		String METHOD_NAME = "getMixLogForUpdate";
		log.entering(CLASS_NAME, METHOD_NAME);

		Teesp09Mixlog result = null;
		Teesp09Mixlog pk = new Teesp09Mixlog();

		pk.setEesp09MlogEffectiveDateY(fecha);
		pk.setEesp09PlantCodeC(plant);
		pk.setEesp09VehicleCodeC(vehiclelin);
		pk.setEesp09MlogSequenceK(seqNumber);

		result = (Teesp09Mixlog) super.getObjForUpdate(pk);

		log.exiting(CLASS_NAME, METHOD_NAME);
		return result;
	}
		
	public void updateMixLogWhenStart(Teesp09Mixlog teesp09Mixlog, FullEconomicsWslxUser user) {                
			
		String METHOD_NAME = "updateMixLogWhenStart";
		log.entering(CLASS_NAME, METHOD_NAME);
		
		try {	
		
			try {
				
				PersistenceUtil.newTransaction();
				Teesp09Mixlog mixlog = this.getMixLogForUpdate(
						teesp09Mixlog.getEesp09PlantCodeC(), teesp09Mixlog
								.getEesp09VehicleCodeC(), teesp09Mixlog
								.getEesp09MlogEffectiveDateY(),
						teesp09Mixlog.getEesp09MlogSequenceK());
				
			    mixlog.setEesp09MlogStartS(new Timestamp(System
						.currentTimeMillis()));
			    mixlog.setEesp09LastUpdtProcessC(new Timestamp(System
						.currentTimeMillis()));
			    //mixlog.setEesp09LastUpdtProcessC("MIXPROC");
				mixlog.setEesp09LastUpdtS(new Timestamp(System
						.currentTimeMillis()));
				mixlog.setEesp09LastUpdtUserC(user.getId());
				PersistenceUtil.commitTransaction();
				
			} catch (Exception e) {
	
				log.logp(
								Level.SEVERE,
								CLASS_NAME,
								METHOD_NAME,
								"ERROR AL PROCESAR EL MIXLOG, continuo con el siguiente",
								e);
				String descripcion = e.getMessage();
				String typeCode = FullEconomicsPrs.CODE.MIX_EVENT_TYPE_CODE_ERROR;
				this.saveMixLogEvent(teesp09Mixlog, user, null, null,
						teesp09Mixlog.getEesp09PlantCodeC(), descripcion, typeCode);
			} 
			
		} catch (Exception e) {
	
			try {
				PersistenceUtil.rollbackTransaction();
			} catch (PersistenceException rollbackEx) {
				rollbackEx.printStackTrace();
			}
	
			log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
					"Create Process Mix Exception", e);
			
		}
	
		log.exiting(CLASS_NAME, METHOD_NAME);
				
	}
	
	public void updateMixLogWhenFinish(Teesp09Mixlog teesp09Mixlog, FullEconomicsWslxUser user) {
		
		String METHOD_NAME = "updateMixLogWhenFinish";
		log.entering(CLASS_NAME, METHOD_NAME);
		
        try {
        	
    		try {
    			PersistenceUtil.newTransaction();
    			// Vuelve a traer el registro que se trajo al inicio para actualizar el estado final
    			Teesp09Mixlog mixlog = this.getMixLogForUpdate(
    					teesp09Mixlog.getEesp09PlantCodeC(), teesp09Mixlog
    							.getEesp09VehicleCodeC(), teesp09Mixlog
    							.getEesp09MlogEffectiveDateY(),
    					teesp09Mixlog.getEesp09MlogSequenceK());
    			mixlog.setEesp09LastUpdtProcessC(new Timestamp(System
    					.currentTimeMillis()));
    			//mixlog.setEesp09LastUpdtProcessC("MIXPROC");
    			mixlog.setEesp09LastUpdtS(new Timestamp(System
    					.currentTimeMillis()));
    			mixlog.setEesp09MlogEndS(new Timestamp(System
    					.currentTimeMillis()));
    			mixlog.setEesp09LastUpdtUserC(user.getId());
    			mixlog
    					.setEesp09MlogProcStatusCodeC(FullEconomicsPrs.CODE.MIX_LOG_STATUS_SUCCESFULL);
    			PersistenceUtil.commitTransaction();

    		} catch (Exception e) {
    			log
    			.logp(
    					Level.SEVERE,
    					CLASS_NAME,
    					METHOD_NAME,
    					"ERROR AL PROCESAR EL MIXLOG, continuo con el siguiente",
    					e);
    	        String descripcion = e.getMessage();
    	        String typeCode = FullEconomicsPrs.CODE.MIX_EVENT_TYPE_CODE_ERROR;

    	        this.saveMixLogEvent(teesp09Mixlog, user, null, null,
    			teesp09Mixlog.getEesp09PlantCodeC(), descripcion, typeCode);
    		}
        	
        }
		catch (Exception e) {

			try {
				PersistenceUtil.rollbackTransaction();
			} catch (PersistenceException rollbackEx) {
				rollbackEx.printStackTrace();
			}

			log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
					"Create Process Mix Exception", e);
		}
		
		log.exiting(CLASS_NAME, METHOD_NAME);
   }
	
	public void saveMixLogEvent(Teesp09Mixlog teesp09Mixlog,



			FullEconomicsWslxUser user, Ncas104SfiVw ncas104SfiVw,
			Teesp01Part teesp01Part, Teesg01Plant teesg01Plant,
			String descripcion, String typeCode) throws PersistenceException {

		MixLogEventDao mixLogEventDao = new MixLogEventDao();

		Teesp10Mixevent teesp10Mixevent = new Teesp10Mixevent();
		teesp10Mixevent.setEesp09MixLog(teesp09Mixlog);
		teesp10Mixevent.setEesp10CreateProcessC("CALCMIX");
		teesp10Mixevent.setEesp10CreateS(new Timestamp(System
				.currentTimeMillis()));
		teesp10Mixevent.setEesp10CreateUserC(user.getId());
		teesp10Mixevent.setEesp10LastUpdtProcessC(user.getId());
		teesp10Mixevent.setEesp10LastUpdtS(new Timestamp(System
				.currentTimeMillis()));
		teesp10Mixevent.setEesp10LastUpdtUserC(user.getId());
		teesp10Mixevent.setEesp10MevntMessageDescripX(descripcion);
		teesp10Mixevent.setEesp10MevntTypeCodeC(typeCode);

		Integer seqNumberEvent = (mixLogEventDao.getMax(new Teesp10Mixevent(),
				null, null, "eesp10MevntSequenceK") + 1);
		teesp10Mixevent.setEesp10MevntSequenceK(seqNumberEvent);

		teesp10Mixevent.setEesp10Part(teesp01Part);
		teesp10Mixevent.setEesp10PlantCodeC(teesg01Plant);
		teesp10Mixevent.setEesp10SfiCodeC(ncas104SfiVw);

		PersistenceUtil.newTransaction();
		mixLogEventDao.createMixLogEvent(teesp10Mixevent);
		PersistenceUtil.commitTransaction();
	}


}
